import 'package:flutter/material.dart';

class TextFiledUtil {

  /// 填充数据
  /// [keepOffset] 保持原来的光标位置
  static setValue(TextEditingController controller, String value, {int? offset, bool keepOffset = false}) {
    var oldOffset = controller.selection.baseOffset;
    controller.text = value;
    var validOffset = offset ?? (keepOffset ? oldOffset : value.length);
    if (validOffset > value.length) {
      validOffset = value.length;
    }
    controller.selection = TextSelection.fromPosition(TextPosition(
        affinity: TextAffinity.downstream,
        offset: validOffset));
  }

  /// 清空当前焦点
  static clearFocus(BuildContext context) {
    FocusNode focusNode = FocusNode();
    FocusScope.of(context).requestFocus(focusNode);
  }

  /// 关闭键盘
  static void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }
}
